/**@author: Administrator
 * @date: 2013-3-5
 * @Description:
 */
package org.benxiong.iplay.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import org.benxiong.iplay.R;
import org.benxiong.iplay.http.request.FileRespHandler;
import org.benxiong.iplay.http.request.RequestFactory;
import org.benxiong.iplay.model.UserPhoto;
import org.benxiong.iplay.model.UserProfile;
import org.benxiong.iplay.ui.BaseActivity;
import org.benxiong.iplay.ui.component.UserPhotoThumbnail;
import org.benxiong.iplay.ui.shared.ViewSinglePhotoActivity;
import org.benxiong.iplay.util.GlobalVar;
import org.benxiong.iplay.util.ImageUtil;
import org.benxiong.iplay.util.LogX;
import org.benxiong.iplay.util.MeasurementUtil;
import org.benxiong.iplay.util.ObjectConverter;
import org.benxiong.iplay.util.PathUtil;
import org.benxiong.iplay.util.ToastUtil;
import org.benxiong.iplay.util.Utils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.polites.android.GestureImageView;

/**
 * @author Administrator
 * 
 */
public class ProfileInfoFragment extends BaseFragment implements OnClickListener {
	private ImageView	coverV;
	private ImageView	avatorV;
	// text without title
	private TextView	nameV;
	private TextView	dobV;
	private TextView	heiweightV;
	private TextView	countryV;
	private TextView	placeV;
	private TextView	roleV;
	private TextView	relationV;
	private TextView	lookingForV;
	private TextView	langV;
	private TextView	buildV;
	private TextView	enthV;
	private TextView	facebookV;
	private TextView	twitterV;
	private TextView	weiboV;
	private TextView	wechatV;
	private TextView	insV;
	private TextView	lineV;

	// text with title
	private TextView	statusV;
	private TextView	introV;
	private TextView	privateIntroV;
	private TextView	myTypeV;

	private String		username;

	private GridLayout	galleryV;

	// user profile data
	private UserProfile	profile;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(R.layout.profile, null);

		nameV = (TextView) view.findViewById(R.id.name);
		dobV = (TextView) view.findViewById(R.id.dob);
		heiweightV = (TextView) view.findViewById(R.id.weiheight);
		countryV = (TextView) view.findViewById(R.id.country);
		placeV = (TextView) view.findViewById(R.id.place);
		roleV = (TextView) view.findViewById(R.id.role);
		relationV = (TextView) view.findViewById(R.id.relation);
		lookingForV = (TextView) view.findViewById(R.id.lookingFor);
		langV = (TextView) view.findViewById(R.id.lang);
		buildV = (TextView) view.findViewById(R.id.build);
		enthV = (TextView) view.findViewById(R.id.enthnicity);
		facebookV = (TextView) view.findViewById(R.id.facebook);
		twitterV = (TextView) view.findViewById(R.id.twitter);
		weiboV = (TextView) view.findViewById(R.id.weibo);
		wechatV = (TextView) view.findViewById(R.id.wechat);
		insV = (TextView) view.findViewById(R.id.instagram);
		lineV = (TextView) view.findViewById(R.id.line);

		statusV = (TextView) view.findViewById(R.id.status);
		introV = (TextView) view.findViewById(R.id.intro);
		privateIntroV = (TextView) view.findViewById(R.id.privateIntro);
		myTypeV = (TextView) view.findViewById(R.id.myType);

		avatorV = (ImageView) view.findViewById(R.id.avator);
		avatorV.setOnClickListener(this);
		coverV = (ImageView) view.findViewById(R.id.cover);

		galleryV = (GridLayout) view.findViewById(R.id.gallery);
		return view;
	}

	private void loadAvator() {
		String url = PathUtil.profilePictureUrl(username, profile.getAvatarVersion());
		LogX.print(url);

		// load avatar picture
		RequestFactory.getInstance().getPic(url, new BinaryHttpResponseHandler(RequestFactory.allowedImgTypes) {

			@Override
			public void onSuccess(byte[] data) {
				if (data == null)
					return;
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				avatorV.setImageBitmap(bitmap);
			}

			@Override
			public void onFailure(Throwable arg0, byte[] arg1) {
				super.onFailure(arg0, arg1);
				ToastUtil.toast(R.string.load_fail);
			}
		});
	}

	private void loadCover() {
		// load cover
		String url = PathUtil.coverPictureUrl(username, profile.getCoverVersion());
		RequestFactory.getInstance().getPic(url, new BinaryHttpResponseHandler(RequestFactory.allowedImgTypes) {

			@Override
			public void onSuccess(byte[] data) {
				if (data == null) {
					return;
				}
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				coverV.setImageBitmap(bitmap);
			}

			@Override
			public void onFailure(Throwable arg0, byte[] arg1) {
				// TODO Auto-generated method stub
				super.onFailure(arg0, arg1);
				ToastUtil.toast(R.string.load_fail);
			}
		});
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		username = activity.getIntent().getStringExtra("username");
	}

	@Override
	public void onStart() {
		super.onStart();
		reqProfileData();
	}

	private void reqProfileData() {
		profile = GlobalVar.dataArchive.getUserProfile(username);
		if (profile != null) {
			try {
				bindData(profile);
				loadCover();
				loadAvator();
				return;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		showLoading();
		RequestParams rParam = new RequestParams();
		rParam.put("username", username);
		final BaseActivity ba = (BaseActivity) this.getActivity();

		RequestFactory.getInstance().post(RequestFactory.URL_GET_PROFILE, rParam, new AsyncHttpResponseHandler() {

			public void onSuccess(String resp) {
				if (!ba.active) {
					LogX.print("activity is not running .... cancel render");
					return;
				}

				try {
					JSONObject json = new JSONObject(resp);
					if (shouldProcess(json)) {
						LogX.print(json.toString(2));
						UserProfile _profile = ObjectConverter.jsonToUserProfile(json);
						GlobalVar.dataArchive.getUserProfilesMap().put(username, _profile);
						profile = _profile;
						bindData(profile);
						loadCover();
						loadAvator();
					} else {
						getActivity().finish();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(Throwable arg0, String arg1) {
				super.onFailure(arg0, arg1);
				showRequestFailMsg(arg1);
			}

		});
	}

	private void bindData(UserProfile profile) throws JSONException {
		LogX.print(profile.toString());
		boolean isMyself = username.equalsIgnoreCase(GlobalVar.userName);
		// render to views
		nameV.setText(username);

		SharedPreferences sp = this.getActivity().getSharedPreferences("org.benxiong.iplay_preferences", Context.MODE_PRIVATE);
		if (sp.getString("unit", "0").equals("0")) {
			String text = "";
			if (profile.getHeightInch() != null)
				text = text + MeasurementUtil.inchToTxt((float) profile.getHeightInch());
			if (profile.getWeightPounds() != null)
				text = text + "\n" + profile.getWeightPounds() + " pounds";
			if (!text.equals(""))
				heiweightV.setText(text);
			else
				heiweightV.setVisibility(View.GONE);
		} else {
			String text = "";
			if (profile.getHeight() != null)
				text = text + profile.getHeight() + " cm ";
			if (profile.getWeight() != null)
				text = text + profile.getWeight() + " kg";
			if (!text.equals(""))
				heiweightV.setText(text);
			else
				heiweightV.setVisibility(View.GONE);
		}

		int size = (int) this.getActivity().getResources().getDimension(R.dimen.profile_img_size);

		// LayoutParams lp = new LayoutParams();
		// lp.width = size;
		// lp.height = size;
		// lp.setMargins(2, 2, 2, 2);
		List<String> photoUrls = new ArrayList<String>();
		for (UserPhoto uphoto : profile.getPublicPhotos()) {
			photoUrls.add(uphoto.getStandardUrl());
		}
		if (!profile.isUnlocked()) {
			for (UserPhoto uphoto : profile.getPrivatePhotos()) {
				photoUrls.add(uphoto.getStandardUrl());
			}
		}

		String[] urls = photoUrls.toArray(new String[photoUrls.size()]);
		ViewPhotos listener = new ViewPhotos(this.getActivity(), urls, 0);
		int index = 0;
		for (UserPhoto uphoto : profile.getPublicPhotos()) {
			LinearLayout ll = new LinearLayout(this.getActivity());
			LayoutParams lp = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
			lp.setMargins(3, 3, 3, 3);
			ll.addView(new UserPhotoThumbnail(getActivity(), uphoto, listener, true, index++), lp);
			galleryV.addView(ll, size, size);
		}

		for (UserPhoto uphoto : profile.getPrivatePhotos()) {
			LinearLayout ll = new LinearLayout(this.getActivity());
			LayoutParams lp = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
			lp.setMargins(3, 3, 3, 3);
			ll.addView(new UserPhotoThumbnail(getActivity(), uphoto, listener, isMyself ? true : profile.isUnlocked(), index++), lp);

			galleryV.addView(ll, size, size);
		}

		if (Utils.isEmpty(profile.getDob())) {
			dobV.setVisibility(View.GONE);
		} else {
			dobV.setText(profile.getDob());
		}

		if (Utils.ignoreIndex(profile.getRoleIndex())) {
			roleV.setVisibility(View.GONE);
		} else {
			roleV.setText(this.getResources().getStringArray(R.array.role)[profile.getRoleIndex()]);
		}

		if (Utils.ignoreIndex(profile.getRelationshipIndex())) {
			relationV.setVisibility(View.GONE);
		} else {
			relationV.setText(this.getResources().getStringArray(R.array.relationship)[profile.getRelationshipIndex()]);
		}

		if (Utils.ignoreIndex(profile.getBuildIndex())) {
			buildV.setVisibility(View.GONE);
		} else {
			buildV.setText(this.getResources().getStringArray(R.array.build)[profile.getBuildIndex()]);
		}

		if (Utils.ignoreIndex(profile.getEthnicityIndex())) {
			enthV.setVisibility(View.GONE);
		} else {
			enthV.setText(this.getResources().getStringArray(R.array.enthnicity)[profile.getEthnicityIndex()]);
		}

		if (Utils.isEmpty(profile.getCountry())) {
			countryV.setVisibility(View.GONE);
		} else {
			countryV.setText("From " + profile.getCountry());
		}

		if (Utils.isEmpty(profile.getPlace())) {
			placeV.setVisibility(View.GONE);
		} else {
			placeV.setText("At " + profile.getPlace());
		}

		String lookingForStr = ObjectConverter.indexesToString(profile.getLookingFor(), this.getResources().getStringArray(R.array.lookingfor));
		if (Utils.isEmpty(lookingForStr)) {
			lookingForV.setVisibility(View.GONE);
		} else {
			lookingForV.setText("Looking For " + lookingForStr);
		}

		String langStr = ObjectConverter.indexesToString(profile.getLang(), this.getResources().getStringArray(R.array.language));
		if (Utils.isEmpty(langStr)) {
			langV.setVisibility(View.GONE);
		} else {
			langV.setText("Speak " + langStr);
		}

		if (Utils.isEmpty(profile.getFacebook())) {
			facebookV.setVisibility(View.GONE);
		} else {
			facebookV.setText("Facebook: \nhttp://fb.com/" + profile.getFacebook());
		}

		if (Utils.isEmpty(profile.getTwitter())) {
			twitterV.setVisibility(View.GONE);
		} else {
			twitterV.setText("Twitter: @" + profile.getTwitter());
		}

		if (Utils.isEmpty(profile.getWeibo())) {
			weiboV.setVisibility(View.GONE);
		} else {
			weiboV.setText("Weibo 微博: @" + profile.getWeibo());
		}

		if (Utils.isEmpty(profile.getWechat())) {
			wechatV.setVisibility(View.GONE);
		} else {
			wechatV.setText("Wechat 微信: @" + profile.getWechat());
		}

		if (Utils.isEmpty(profile.getInstagram())) {
			insV.setVisibility(View.GONE);
		} else {
			insV.setText("Instagram: @" + profile.getInstagram());
		}

		if (Utils.isEmpty(profile.getLine())) {
			lineV.setVisibility(View.GONE);
		} else {
			lineV.setText("Line: @" + profile.getLine());
		}

		statusV.setText(profile.getStatus());
		introV.setText(profile.getIntro());
		myTypeV.setText(profile.getMyType());

		// TODO: base on 'unlocked'
		privateIntroV.setText(profile.getPrivateIntro());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.avator:
			final GestureImageView imgV = new GestureImageView(this.getActivity());
			imgV.setMinScale((float) 0.5);
			imgV.setMaxScale(3);
			imgV.setStrict(false);
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			imgV.setLayoutParams(params);

			showLoading();
			String url = PathUtil.profilePictureOfStandardSizeUrl(GlobalVar.userName, null);
			RequestFactory.getInstance().get(url, new FileRespHandler() {

				@Override
				public void onSuccess(byte[] data) {
					hideLoading();
					Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
					imgV.setImageBitmap(bitmap);
					ImageUtil.showImageViewInDialog(imgV, ProfileInfoFragment.this.getActivity());
				}

				@Override
				public void onFailure() {
					hideLoading();
					ToastUtil.toast(R.string.load_fail);
				}
			});

			break;
		}

	}

	public class ViewPhotos implements View.OnClickListener {
		private String[]	urls;
		private int			startIndex;
		private Context		context;

		public ViewPhotos(Context context, String[] urls, int startIndex) {
			this.urls = urls;
			this.startIndex = startIndex;
			this.context = context;
		}

		@Override
		public void onClick(View v) {
			UserPhotoThumbnail view = (UserPhotoThumbnail)v;
			Intent _intent = new Intent(context, ViewSinglePhotoActivity.class);
			_intent.putExtra("urls", this.urls);
			_intent.putExtra("currentIndex", view.getIndex());
			context.startActivity(_intent);
		}
	}

}
